package com.rem.cloudalibaba.controller;

import com.rem.cloudalibaba.entity.CommonResult;
import com.rem.cloudalibaba.entity.Product;
import com.rem.cloudalibaba.service.OrderService;
import com.rem.cloudalibaba.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 直接根据http 访问ip调用
 *
 * @author Rem
 * @date 2021-07-12
 */

@RestController
@RefreshScope
@Slf4j
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    /**
     * 根据商品创建订单
     *
     * @param pid
     */
    @GetMapping("/createOrder/{pid}")
    public CommonResult createOrder(@PathVariable("pid") Integer pid) {
        CommonResult<Product> productCommonResult = productService.getProduct(pid);
        log.info("通过feign调用的数据：" + productCommonResult);

        if (productCommonResult.getCode().equals(0)) {
            orderService.createOrder(productCommonResult.getData());
            return CommonResult.ok();
        }
        return CommonResult.error();
    }


    /**
     * 测试seata
     * 创建订单 扣减库存
     *
     * @param pid
     * @param num
     * @return
     */
    @PostMapping("/createOrder/{pid}/{num}")
    public CommonResult createOrder(@PathVariable("pid") Integer pid, @PathVariable("num") Integer num) {
        try {
            orderService.createOrder(pid, num);
            return CommonResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.error();
    }


    @GetMapping("/test/{id}")
    public CommonResult<String> test(@PathVariable("id") Integer id) {
        return productService.test(id);

    }


}
